package www.openteam.com.ui.policy;


import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import www.openteam.com.R;
import www.openteam.com.adapter.policy.SendRcvApprlAdp;
import www.openteam.com.adapter.policy.SendRcvApprlChildAdp;
import www.openteam.com.base.mBaseFragment;
import www.openteam.com.bean.ApprlSuccess;
import www.openteam.com.bean.SendRcvPoductMsg;
import www.openteam.com.bean.SendRcvUserMsg;
import www.openteam.com.contract.policy.SendRcvApprlContract;
import www.openteam.com.presenter.policy.SendRcvApprlPrst;
import www.openteam.com.tool.ToastUtil;
import www.openteam.com.view.policy.MEXpandableLinearLayout;


/**
 * A simple {@link Fragment} subclass.
 */
public class SendRcvApprlFragment extends mBaseFragment<SendRcvApprlPrst>
        implements SendRcvApprlContract.SendRcvApprlView {


    @Bind(R.id.tv_1)
    TextView tv1;
    @Bind(R.id.ed_1)
    EditText ed1;
    @Bind(R.id.tv_2)
    TextView tv2;
    @Bind(R.id.ed_2)
    Spinner ed2;
    @Bind(R.id.tv_3)
    TextView tv3;
    @Bind(R.id.ed_4)
    EditText ed4;
    @Bind(R.id.tv_4)
    TextView tv4;
    @Bind(R.id.ed_3)
    EditText ed3;
    @Bind(R.id.btn1)
    Button btn1;
    @Bind(R.id.btn2)
    Button btn2;
    @Bind(R.id.btn3)
    Button btn3;
    @Bind(R.id.recyclerview)
    RecyclerView recyclerview;
    @Bind(R.id.query_btn)
    Button queryBtn;
    @Bind(R.id.child_recycleview)
    RecyclerView childRecycleview;
    @Bind(R.id.expand_line)
    MEXpandableLinearLayout expand_line;
    private ArrayList<String> ids;
    ArrayList<List<SendRcvPoductMsg.DataBeanX.DataBean>> dataBeans;
    private SendRcvApprlAdp sendRcvApprlAdp;
    private SendRcvApprlChildAdp apprlChildAdp;
    private String TAG = getClass().getSimpleName();
    Boolean ischeck = mySetting.getBoolean("chk", false);
    private List<SendRcvUserMsg.DataBeanX.DataBean> userMsgdata;
    private int approval = 0;
    private int changePosition = 0;
    private int finalm = -1;
    private String checker;
    private String checkDate;

    public SendRcvApprlFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_send_rcv_apprl, container, false);
        ButterKnife.bind(this, view);
        mPresenter = loadPresenter();
        initData();
        initListener();
        initView();
        return view;
    }

    @Override
    protected void initData() {
        if (mPresenter != null)
            mPresenter.attachView(this);
        recyclerview.setLayoutManager(new LinearLayoutManager(getContext()));
        LinearLayoutManager layout = new LinearLayoutManager(getContext());
        layout.setOrientation(LinearLayout.HORIZONTAL);
        childRecycleview.setLayoutManager(layout);
        mProgressDialog = new ProgressDialog(getContext());
        dataBeans = new ArrayList<>();
        apprlChildAdp = new SendRcvApprlChildAdp(getContext());
//        expand_line.registerViewObserver(queryBtn);
    }

    @Override
    protected void initListener() {
        ed4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ed4.setTag(ed4);
                selectCalendar(ed4);
            }
        });
        ed3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ed3.setTag(ed3);
                selectCalendar(ed3);
            }
        });
    }

    public void selectCalendar(final TextView v) {
        Calendar calendar = Calendar.getInstance();
        DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                v.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        datePickerDialog.show();
    }

    public String getCurrentTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// HH:mm:ss
        Date date = new Date(System.currentTimeMillis());
        return simpleDateFormat.format(date).toString();

    }

    @Override
    protected void initView() {
        final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        int current_day = c.get(Calendar.DAY_OF_MONTH);
        int current_month = c.get(Calendar.MONTH);
        int current_year = c.get(Calendar.YEAR);
        c.set(current_year, current_month, current_day);
        ed3.setText(df.format(c.getTime()));
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {//一周内
                Calendar c = Calendar.getInstance();
                int current_day = c.get(Calendar.DAY_OF_MONTH);
                int current_month = c.get(Calendar.MONTH);
                int current_year = c.get(Calendar.YEAR);
                c.set(current_year, current_month, current_day);
                c.add(Calendar.DATE, -7);
                ed4.setText(df.format(c.getTime()));
            }
        });

        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {//一月内
                Calendar c = Calendar.getInstance();
                int current_day = c.get(Calendar.DAY_OF_MONTH);
                int current_month = c.get(Calendar.MONTH) - 1;
                int current_year = c.get(Calendar.YEAR);
                c.set(current_year, current_month, current_day);
//                ed_3.setText(df.format(c.getTime()));
//                c.add(Calendar.DATE, 0);
                ed4.setText(df.format(c.getTime()));
            }
        });

        btn3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {//一年内
                Calendar c = Calendar.getInstance();
                int current_day = c.get(Calendar.DAY_OF_MONTH);
                int current_month = c.get(Calendar.MONTH);
                int current_year = c.get(Calendar.YEAR) - 1;
                c.set(current_year, current_month, current_day);
//                ed_3.setText(df.format(c.getTime()));
//                c.add(Calendar.DATE, 0);
                ed4.setText(df.format(c.getTime()));
            }
        });
    }

    @Override
    protected void otherViewClick(View view) {

    }

    @Override
    protected SendRcvApprlPrst loadPresenter() {
        return new SendRcvApprlPrst();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        dataBeans.clear();
//        ids.clear();
    }

    @Override
    public void onRefresh() {

    }

    @Override
    public void findUserMsg(SendRcvUserMsg sendRcvUserMsg) {
        userMsgdata = sendRcvUserMsg.getData().getData();
        ids = new ArrayList<>();
        for (SendRcvUserMsg.DataBeanX.DataBean databean : userMsgdata) {
            ids.add(databean.getId());
        }

        int size = ids.size();
//        for (int i = 0; i < size; ++i) {
//            Log.e(TAG, "findPuductMsgType:**  i" + ids.get(i));
//            mPresenter.findPouductMsgType(ids.get(i));
//        }
        mPresenter.findPouductMsgType(ids);
        sendRcvApprlAdp = new SendRcvApprlAdp(getContext(), userMsgdata);
        sendRcvApprlAdp.setIscheck(ischeck);

//        getchildMsg(ids);

    }

    @Override
    public void findUserMsgFail(String msg) {
        Log.e(TAG, "findUserMsgFail: " + msg);
        ToastUtil.showToast(getContext(), msg);
    }

    @Override
    public void findPuductMsgType(SendRcvPoductMsg sendRcvPoductMsg) {
        finalm++;
        List<SendRcvPoductMsg.DataBeanX.DataBean> dataBeanList = new ArrayList<>();
        if (null == sendRcvPoductMsg) {
            SendRcvPoductMsg.DataBeanX.DataBean dataBean = new SendRcvPoductMsg.DataBeanX.DataBean();
            dataBean.setAddressLst("");
            dataBean.setAllsum("");
            dataBean.setAprocedure("");
            dataBean.setCode("");
            dataBean.setGroupname("");
            dataBean.setId(0);
            dataBean.setName("");
            dataBean.setOnumb("");
            dataBean.setOsplanpid(0);
            dataBean.setOsplanrdsno("");
            dataBean.setOtherNote("");
            dataBean.setOtReason("");
            dataBean.setOutMaterial("");
            dataBean.setPartID("");
            dataBean.setPlanMid("");
            dataBean.setPrice("");
            dataBean.setProcID(0);
            dataBean.setProcName("");
            dataBean.setProcno("");
            dataBean.setProcquest("");
            dataBean.setRemark("");
            dataBeanList.add(dataBean);
        } else {
            dataBeanList = sendRcvPoductMsg.getData().getData();
        }
        dataBeans.add(dataBeanList);
//        Log.e(TAG, "--findPuductMsgType: " + "ids.size()" + ids.get(finalm));
//        Log.e(TAG, "--findPuductMsgType: " + "finalm" + finalm);
//        Log.e(TAG, "findPuductMsgType: " + "dataBeans.size()" + dataBeanList.get(0).getProcno() );

        if (dataBeans.size() == 1) {
            childRecycleview.setVisibility(View.VISIBLE);
            apprlChildAdp.setDataBeans(dataBeans.get(0));
            apprlChildAdp.notifyDataSetChanged();
            childRecycleview.setAdapter(apprlChildAdp);
        }

        if (ids.size() == dataBeans.size()) {
//            Log.e(TAG, "findPuductMsgType:=== " + "ids.size()" + ids.size());
//            Log.e(TAG, "findPuductMsgType: ===" + "dataBeans.size()" + dataBeans.size());
            mProgressDialog.cancel();
            recyclerview.setAdapter(sendRcvApprlAdp);
            sendRcvApprlAdp.setSendRcvApprlAdpClick(new SendRcvApprlAdp.SendRcvApprlAdpClick() {
                @Override
                public void postData(int postion) {
                    List<SendRcvPoductMsg.DataBeanX.DataBean> dataBeanList1 = dataBeans.get(postion);
                    apprlChildAdp.setDataBeans(dataBeanList1);
                    apprlChildAdp.notifyDataSetChanged();
                    childRecycleview.setAdapter(apprlChildAdp);
                }
            });
            sendRcvApprlAdp.registerAdapterDataObserver(adapterDataObserver);
            sendRcvApprlAdp.setSendRcvApprlAdpAudit(new SendRcvApprlAdp.SendRcvApprlAdpAudit() {
                @Override
                public void postData(int postion, Button button) {
                    SendRcvUserMsg.DataBeanX.DataBean dataBean = userMsgdata.get(postion);
                    int status = dataBean.getStatus();
                    if (status == 0 || status == 1) {
                        if (!ischeck) {
                            ToastUtil.showToast(getContext(), "该用户没有审核权限");
                        } else {
                            if (status == 0) {//进行审核
                                checker = mySetting.getString("mName", "");
                                checkDate = getCurrentTime();
                                mPresenter.audit(checker, checkDate + "", dataBean.getId() + "");
                                changePosition = postion;
                                mProgressDialog.show();
                            } else if (status == 1) {//进行反审核
                                mPresenter.reverseAudit(dataBean.getId() + "");
                                changePosition = postion;
                                mProgressDialog.show();
                            }
                        }
                    } else {
                        ToastUtil.showToast(getContext(), "此相关记录已进入下一流程，无法取消审核");
                    }
                }
            });
        }

    }


    RecyclerView.AdapterDataObserver adapterDataObserver = new RecyclerView.AdapterDataObserver() {
        public void onItemRangeChanged(int positionStart, int itemCount) {
            if (approval == 0) {
                sendRcvApprlAdp.changeData(changePosition, 0, null, null);
            } else {
                sendRcvApprlAdp.changeData(changePosition, 1, checker, checkDate);
            }
        }
    };

    @Override
    public void findPoductMsgFail(String msg) {
        mProgressDialog.cancel();
        Log.e(TAG, "findPoductMsgFail: " + msg);
//        ToastUtil.showToast(getContext(),msg);
    }

    @Override
    public void audit(ApprlSuccess apprlSuccess) {
        mProgressDialog.cancel();
        ToastUtil.showToast(getContext(), "审核成功");
        approval = 1;
        sendRcvApprlAdp.notifyItemChanged(changePosition);
    }

    @Override
    public void auditFail(String msg) {
        mProgressDialog.cancel();
        ToastUtil.showToast(getContext(), msg);
    }

    @Override
    public void reverseAudit(ApprlSuccess apprlSuccess) {
        mProgressDialog.cancel();
        ToastUtil.showToast(getContext(), "取消审核成功");
        approval = 0;
        checkDate = null;
        checker = null;
        sendRcvApprlAdp.notifyItemChanged(changePosition);
    }

    @Override
    public void reverseAuditFail(String msg) {
        mProgressDialog.cancel();
        ToastUtil.showToast(getContext(), msg);
    }

    @OnClick(R.id.query_btn)
    public void onViewClicked() {
        String ischecked = "0";
        int s = ed2.getSelectedItemPosition();


        mPresenter.findUserMsg(ed1.getText().toString(), ed4.getText().toString(), ed3.getText().toString(), s + "");
        dataBeans.clear();
        finalm = -1;
        mProgressDialog.show();
    }
}
